package com.example.guiguiapplicatio;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.guiguiapplicatio.databindingBean.Doctor;
import com.example.guiguiapplicatio.api.Interface.AllCallback;
import com.example.guiguiapplicatio.api.Interface.Api;
import com.example.guiguiapplicatio.api.LoginApi;
import com.example.guiguiapplicatio.util.ResponseBody;
import com.example.guiguiapplicatio.utils.PreferencesUtil;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class LoginActivity extends AppCompatActivity implements AllCallback {

    private EditText etUsername;
    private EditText etPassword;
    private Button btnConfirm;
    private LoginApi loginApi;
    private TextView tvQuickRegister; // Add this
    public String userId;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        checkIsLogining();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        loginApi = new LoginApi();
        loginApi.setallCallback(this);
        etUsername = findViewById(R.id.et_username);
        etPassword = findViewById(R.id.et_password);
        btnConfirm = findViewById(R.id.btn_confirm);


        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String username = etUsername.getText().toString();
                String password = etPassword.getText().toString();
//                loginApi.performLogin(username, password);//原方法
                testLogin(username, password);




//                        authenticateUser(username, password);
            }
        });


//        tvQuickRegister.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                navigateToRegistration(); // Start the registration activity
//            }
//        });
    }

    private void testLogin(String username, String password){
        Api api;
        OkHttpClient client = new OkHttpClient.Builder().

          connectTimeout(6, TimeUnit.SECONDS).build();//用于设置请求超时等限制时间
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(getString(R.string.api))
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        api = retrofit.create(Api.class);
        Doctor doctor =new Doctor();
        doctor.setUsername(username);
        doctor.setPassword(password);
        Call<ResponseBody<Doctor>> call =api.login(doctor);
        call.clone().enqueue(new Callback<ResponseBody<Doctor>>() {
            @Override
            public void onResponse(Call<ResponseBody<Doctor>> call, Response<ResponseBody<Doctor>> response) {
                if (response.body()!=null){
                    ResponseBody<Doctor> responseBody=response.body();
                    if (responseBody.getCode() == 200){
                        Toast.makeText(LoginActivity.this, "登陆成功", Toast.LENGTH_LONG).show();
                        Doctor doctor1=responseBody.getData();
                        Log.e("onFailure", "onResponse: " + doctor1.getLocation());
                        PreferencesUtil.putInt(LoginActivity.this, "doctor_id", doctor1.getId());
                        PreferencesUtil.putString(LoginActivity.this, "doctor_name", doctor1.getName());

                        Gson gson=new Gson();
                        PreferencesUtil.putString(LoginActivity.this,"doctor_gson",gson.toJson(doctor1));

                        Intent intent = new Intent(LoginActivity.this, MainActivity.class); // 替换成你要跳转的目标 Activity
                        startActivity(intent);
                        finish();

                    }else if (responseBody.getCode() == 0){
                        Toast.makeText(LoginActivity.this, responseBody.getMsg(), Toast.LENGTH_LONG).show();
                    }

                }
            }

            @Override
            public void onFailure(Call<ResponseBody<Doctor>> call, Throwable t) {
                Log.e("onFailure", "onFailure: ！" + t);
                if (LoginActivity.this != null) {
                    Toast.makeText(LoginActivity.this, "网络连接有误", Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    private void checkIsLogining() {
        if (PreferencesUtil.getInt(this, "doctor_id") != -1) {
            Intent intent = new Intent(this, MainActivity.class); // 替换成你要跳转的目标 Activity
            startActivity(intent);
            this.finish();
        }

    }

    private void navigateToRegistration() {
        Intent intent = new Intent(LoginActivity.this, MainActivity.class); // Replace with your registration activity class
        startActivity(intent);
    }


    private void navigateToMainPage(String username) {
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        intent.putExtra("userId", userId);
        intent.putExtra("username", username);
        startActivity(intent);
        finish();
    }


    public void authenticateUser(String username, String password) {
        if (Objects.equals(username, "1") && Objects.equals(password, "1")) {
            Intent intent = new Intent(LoginActivity.this, MainActivity.class); // Replace with your registration activity class
            startActivity(intent);
        }

    }

    @Override
    public void onSuccess(ResponseBody<Object> responseBody) {

        int code = responseBody.getCode();
        if (code == 0) {
            // 登录失败，显示错误消息
            String errorMessage = responseBody.getMsg();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(LoginActivity.this, "登陆失败", Toast.LENGTH_SHORT).show();
                }
            });
        } else if (code == 200) {
            // 登录成功，显示成功消息
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                }
            });
            // 可以在这里跳转到下一个页面或者执行其他逻辑
            // 登录成功，启动新的 Activity
            JsonObject jsonObject = JsonParser.parseString(responseBody.getData().toString()).getAsJsonObject();
//                Log.d("info", "我在这里" + jsonObject.toString());
            int doctor_id = jsonObject.get("id").getAsInt();
            String doctor_name = jsonObject.get("name").getAsString();
            PreferencesUtil.putInt(this, "doctor_id", doctor_id);
            PreferencesUtil.putString(this, "doctor_name", doctor_name);
            Log.e("TAG", "onSuccess:doctor_id doctor_name:" + doctor_id + doctor_name);

            Intent intent = new Intent(this, MainActivity.class); // 替换成你要跳转的目标 Activity
            startActivity(intent);
            finish();
        }

    }

    @Override
    public void onFailure(String errorMessage) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(LoginActivity.this, "响应失败", Toast.LENGTH_SHORT).show();
            }
        });

    }

}
